package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.constant.BussinessResultCodeEnum;
import com.dao.*;
import com.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.model.*;
import com.page.GenericPage;
import com.po.*;
import com.result.Result;
import com.service.SysUserService;
import com.utils.CurrentLoginUserAgent;
import com.utils.SessionUtil;
import com.vo.AdvertisementVO;
import com.vo.CustomerVO;
import com.vo.PermissionRoleVO;
import com.vo.SysUserQueryVO;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.testng.collections.Lists;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: chihaojie
 * @Date: 2019/5/29 16:28
 * @Version 1.0
 * @Note
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AgentMoneyAmountMapper agentMoneyAmountMapper;

    @Autowired
    private PlacedHospitalMapper placedHospitalMapper;

    @Autowired
    private PermissionSysUserRoleMapper permissionSysUserRoleMapper;

    @Autowired
    private PermissionRoleMapper permissionRoleMapper;

    @Autowired
    private  AgentAlipayAccountMapper    agentAlipayAccountMapper;

    @Autowired
    private  AgentAccountMapper  agentAccountMapper;



    @Autowired
    private SysUserBindWechatMapper sysUserBindWechatMapper;


    /**
     * 暂时只可以创建 代理商
     *
     * @param sysUserPO
     * @return
     */
    @Transactional
    @Override
    public Result<SysUser> save(SysUserPO sysUserPO) {
        if (
                ObjectUtils.isEmpty(sysUserPO.getMobile()) ||
                        ObjectUtils.isEmpty(sysUserPO.getPassword()) ||
                        ObjectUtils.isEmpty(sysUserPO.getRealName()) ||
                        ObjectUtils.isEmpty(sysUserPO.getUserName()) ||
                        ObjectUtils.isEmpty(sysUserPO.getRoleId())
        ) {
            return new Result<>().error("参数异常");
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserPO, sysUser);
        Date time = new Date();
        sysUser.setCreateTime(time);
        sysUser.setUpdateTime(time);
        sysUser.setUpdated(sysUser.getCreated());

        Integer currentUserType = SessionUtil.getCurrentUserType();
        Long currentUserId = SessionUtil.getCurrentUserId();
        Long currentUserLeaderId = SessionUtil.getCurrentUserLeaderId();
        switch (currentUserType) {
            case 1:
                //root 用户
                sysUser.setUserType(2);  //代理商
                sysUser.setLeaderId(currentUserId);
                break;
            case 2:
                //代理商
                sysUser.setUserType(3);  //普通用户
                sysUser.setLeaderId(currentUserId);
                break;
            case 3:
                //普通用户
                sysUser.setUserType(3);  //普通用户
                sysUser.setLeaderId(currentUserLeaderId);
                break;
        }
        sysUser.setStatus(1);
        SysUser condition = new SysUser();
        //查询电话
        condition.setMobile(sysUserPO.getMobile());
        List<SysUser> mobileUserList = sysUserMapper.selectByCondition(condition);
        if (!ObjectUtils.isEmpty(mobileUserList)) {
            return new Result<>().error("手机号码已存在");
        }
        //查询用户名
        condition = new SysUser();
        condition.setUserName(sysUserPO.getUserName());
        List<SysUser> userNames = sysUserMapper.selectByCondition(condition);
        if (userNames != null && userNames.size() > 0) {
            return new Result<>().error("用户名已存在");
        }
        sysUserMapper.insertSelective(sysUser);
        //为服务商账号创建财务账号
        //TODO 1、为代理商创建财务账号
        //TODO 2、为代理商绑定支付宝信息
        if (currentUserType.equals(1)) {
            createFinanceAccountForAgent(sysUserPO,sysUser);
        }
        //账号关联角色
        //先删除之前的关系
        permissionSysUserRoleMapper.deleteByAccountId(sysUser.getId());
        // 插入
        PermissionSysUserRole userRole = new PermissionSysUserRole();
        userRole.setUserId(sysUser.getId());
        userRole.setRoleId(sysUserPO.getRoleId());
        permissionSysUserRoleMapper.insert(userRole);
        //代理商  关联医院
        if (sysUser.getUserType() == 2) {
            //关联医院
            if (sysUserPO.getHospitalIds() != null && sysUserPO.getHospitalIds().size() > 0) {
                List<SysUserIdAndHospitalIdPO> list = new ArrayList<>();
                SysUserIdAndHospitalIdPO map = null;
                for (Long hId : sysUserPO.getHospitalIds()) {
                    map = new SysUserIdAndHospitalIdPO();
                    map.setSysUserId(sysUser.getId());
                    map.setHospitalId(hId);
                    list.add(map);
                }
                placedHospitalMapper.updateSysUserIdsById(list);
            }
        }
        return new Result<SysUser>().ok(sysUser);
    }

    private void createFinanceAccountForAgent(SysUserPO sysUserPO, SysUser sysUser) {
        Date  now=new Date();
        AgentAlipayAccountPO alipayAccountPO = sysUserPO.getAlipayAccountPO();
        if(ObjectUtils.isEmpty(alipayAccountPO)|| ObjectUtils.isEmpty(alipayAccountPO.getAliAccount())){
            throw new BusinessException(BussinessResultCodeEnum.AGENT_ALIPAY_ACCOUNT_CANNOT_NULL);
        }
        AgentAlipayAccount  agentAlipayAccount=new AgentAlipayAccount();
        agentAlipayAccount.setUserId(sysUser.getId());
        agentAlipayAccount.setAliAccount(alipayAccountPO.getAliAccount());
        agentAlipayAccount.setAliAccountName(alipayAccountPO.getAliAccountName());
        if(ObjectUtils.isEmpty(alipayAccountPO.getSettleWay())){
            agentAlipayAccount.setSettleWay(2);
        }else agentAlipayAccount.setSettleWay(alipayAccountPO.getSettleWay());
        agentAlipayAccount.setCreateTime(now);
        agentAlipayAccountMapper.insert(agentAlipayAccount);
        AgentAccount  agentAccount=new AgentAccount();
        agentAccount.setUserId(sysUser.getId());
        agentAccount.setAmount(new BigDecimal("0.00"));
        agentAccount.setAccountName(sysUser.getRealName());
        agentAccount.setBalanceAmount(new BigDecimal("0.00"));
        agentAccount.setSettledAmount(new BigDecimal("0.00"));
        agentAccount.setLastTermBalance(new BigDecimal("0.00"));
        agentAccount.setCreateTime(now);
        agentAccountMapper.insert(agentAccount);
    }

    @Override
    @Transactional
    public Result<Boolean> removeById(Long id) {
        //先删除之前的关系
        permissionSysUserRoleMapper.deleteByAccountId(id);
        sysUserMapper.deleteByPrimaryKey(id);
        sysUserBindWechatMapper.deleteByUserId(id);

        return new Result<>().ok();
    }

    @Override
    public Result<Boolean> modifyById(SysUserModifyPO sysUserModifyPO) {
        if (StringUtils.isEmpty(sysUserModifyPO.getId())) {
            return new Result<>().error("参数异常");
        }
        //判断用户是否存在
        SysUser s = sysUserMapper.selectByPrimaryKey(sysUserModifyPO.getId());
        if (s == null) {
            return new Result<>().error("ID 为" + sysUserModifyPO.getId() + "的用户不存在");
        }
        //判断手机号是否重复
        if (!StringUtils.isEmpty(sysUserModifyPO.getMobile()) && !s.getMobile().equals(sysUserModifyPO.getMobile())) {
            SysUser condition = new SysUser();
            condition.setMobile(sysUserModifyPO.getMobile());
            List<SysUser> sysUsers = sysUserMapper.selectByCondition(condition);
            if (sysUsers != null && sysUsers.size() > 0 && sysUsers.get(0).getId() != sysUserModifyPO.getId()) {
                return new Result<>().error("电话号码已存在");
            }
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserModifyPO, sysUser);
        Date time = new Date();
        sysUser.setUpdateTime(time);
        sysUser.setUpdated(sysUserModifyPO.getUpdated());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        //账号关联角色
        Long roleId = sysUserModifyPO.getRoleId();
//        List<Long> roleIdList = sysUserModifyPO.getRoleIdList();
        permissionSysUserRoleMapper.deleteByAccountId(sysUser.getId());
        PermissionSysUserRole userRole = new PermissionSysUserRole();
        userRole.setUserId(sysUser.getId());
        userRole.setRoleId(roleId);
        permissionSysUserRoleMapper.insert(userRole);
        return new Result<>().ok();
    }

    @Override
    public Result<GenericPage<SysUserQueryVO>> queryAll(SysUserQueryPO sysUserQueryPO) {
        int pageNo = sysUserQueryPO.getPageNo() == 0 ? 1 : sysUserQueryPO.getPageNo();
        int pageSize = sysUserQueryPO.getPageSize() == 0 ? 10 : sysUserQueryPO.getPageSize();
//        PageHelper.startPage(pageNo, pageSize);
        List<SysUserQueryVO> list = new ArrayList<>();
        SysUser sysUser = new SysUser();
        Long businessId = CurrentLoginUserAgent.getBusinessId();
        sysUser.setLeaderId(businessId);
        BeanUtils.copyProperties(sysUserQueryPO, sysUser);
        PageInfo<CustomerVO> pageInfo = PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> {
            List<SysUser> sysUsers = sysUserMapper.selectByCondition(sysUser);
            SysUserQueryVO vo = null;
            for (SysUser s : sysUsers) {
                vo = new SysUserQueryVO();
                BeanUtils.copyProperties(s, vo);
                vo.setPassword("");
                list.add(vo);
            }
        });
        GenericPage<SysUserQueryVO> genericPage = new GenericPage<>(pageSize, pageInfo.getTotal(), list);
        System.out.println("集合大小是：" + list.size());
        System.out.println("分页的总行数是: " + pageInfo.getTotal());
        return new Result<GenericPage<SysUserQueryVO>>().ok(genericPage);
    }

    @Override
    public Result<SysUserQueryVO> queryById(Long id) {
        SysUserQueryVO sysUserQueryVO = new SysUserQueryVO();
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
        if (sysUser == null) {
            return new Result<>().error("用户不存在");
        }
        //查询中间表id
        List<Long> roleIdListByAccountId = permissionSysUserRoleMapper.selectRoleIdListByAccountId(id);
        BeanUtils.copyProperties(sysUser, sysUserQueryVO);
        if (!ObjectUtils.isEmpty(roleIdListByAccountId)) {
            sysUserQueryVO.setRoleId(roleIdListByAccountId.get(0));
        }
        return new Result<SysUserQueryVO>().ok(sysUserQueryVO);
    }
}
